﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using EnOceanReceiver;
using EnOcean;
using EnOcean.Radio.Sensor;

namespace Logger
{
  public partial class LoggerService : ServiceBase
  {
    private Receiver receiver;


    public LoggerService()
    {
      InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
      try
      {
        receiver = new Receiver(null);
        receiver.TelegramReceived += new EventHandler<TelegramReceivedEventArgs>(TelegramReceived);
        receiver.Start();
      }
      catch (Exception e)
      {
        EventLog.WriteEntry(e.ToString(), EventLogEntryType.Error);
      }
    }

   

    protected override void OnStop()
    {
      try
      {
        receiver.Stop();
      }
      catch (Exception e)
      {
        EventLog.WriteEntry(e.ToString(), EventLogEntryType.Error);
      }
    }

    private void TelegramReceived(object sender, TelegramReceivedEventArgs e)
    {
      try
      {
        if (e.Telegram is SensorTelegram)
        {
          Database.StoreSensorTelegram((SensorTelegram)e.Telegram, e.Timestamp);
        }
      }
      catch (Exception ex)
      {
        EventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
      }
    }
  }
}
